package ro.cityprojects.adminloc.service;

import flexjson.JSONSerializer;
import org.springframework.util.StringUtils;
import ro.cityprojects.adminloc.metadata.EntityMetadata;

import java.util.Arrays;

/**
 * BaseService class
 *
 * @author bogdan.solga
 *
 * Date: 18.06.2013, time: 20:17
 */
public class BaseService {
    protected static String[] getOutputFields(String includedFields, String[] defaultFields) {
        String[] included;
        if (!StringUtils.isEmpty(includedFields)) {
            if (includedFields.contains(",")) {
                included = StringUtils.split(includedFields, ",");
            } else {
                included = new String[]{includedFields};
            }
        } else {
            included = defaultFields;
        }

        return included;
    }

    protected static String serialize(Object entities, String[] includedProperties) {
        if (entities == null) {
            throw new IllegalArgumentException("Cannot serialize a null object!");
        }

        JSONSerializer jsonSerializer = new JSONSerializer();

        jsonSerializer.setIncludes(Arrays.asList(includedProperties));
        jsonSerializer.setExcludes(Arrays.asList("*"));

        return jsonSerializer.serialize(entities);
    }

    protected static String getMetadata(EntityMetadata metadata) {
        JSONSerializer jsonSerializer = new JSONSerializer();

        jsonSerializer.exclude("*.class");

        return jsonSerializer.deepSerialize(metadata.getDetails());
    }
}
